<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form-model ref="form" :model="mdl" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                    <a-row :span="24">
                        <a-col :span="12">
                            <a-form-model-item :label="boentI18n('form.name','名称')" prop="name" :labelCol="labelCol" :wrapperCol="wrapperCol">
                                <a-input :placeholder="boentI18n('form.name','名称','input')" @blur.native="getPinyinByName" v-model="mdl.name"/>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-model-item :label="boentI18n('form.alias','标识')" prop="alias" :label-col="labelCol" :wrapper-col="wrapperCol">
                                <a-input :placeholder="boentI18n('form.alias','请输入标识','input')" v-model="mdl.alias"/>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                    <a-row :span="24">
                        <a-col :span="12">
                            <a-form-model-item :label="boentI18n('form.category','分类')" prop="category" :label-col="labelCol"
                                               :wrapper-col="wrapperCol">
                                <rx-category-select cat-key="FORM" :isGrant="true"
                                                    v-if="isShowManageTree" :isAdmin="isManageToTree"
                                                    v-model="mdl.category"></rx-category-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-model-item :label="i18n('form.navPosition','导航栏位置')" prop="navigationPosition" :label-col="labelCol"
                                               :wrapper-col="wrapperCol">
                                <a-radio-group v-model="mdl.navigationPosition" defaultValue="horizontal">
                                    <a-radio value="horizontal">
                                        {{i18n('list.horiz','水平')}}
                                    </a-radio>
                                    <a-radio value="vertical">
                                        {{i18n('list.upright','竖直')}}
                                    </a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                    <a-row :span="24">
                        <a-col :span="12">
                            <a-form-model-item :label="i18n('form.mainsolution','主表单方案')" prop="mainFormSolution" :label-col="labelCol"
                                               :wrapper-col="wrapperCol">
                                <rx-input-button ref="mainFormSolution" v-model="mdl.mainFormSolution"
                                                 :showClose="false" :placeholder="i18n('form.mainsolution','请选择主表单方案','select')"
                                                 @click="setMainFormSolution"></rx-input-button>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                    <a-row :span="24">
                        <a-col :span="24">
                            <a-form-model-item :label="i18n('list.nav','导航')+$ti18('rxList.config','配置')" prop="formSolutions" v-show="mdl.mainFormSolution"
                                               :label-col="labelCol1" :wrapper-col="wrapperCol1">
                                <a-button-group class="addbutton">
                                    <button @click="addRow"><i class="iconfont iconadd"></i></button>
                                    <button @click="removeRows"><i class="iconfont icontrash"></i></button>
                                    <button @click="upRow"><i class="iconfont iconshang"></i></button>
                                    <button @click="downRow"><i class="iconfont iconxia"></i></button>
                                    <button @click="moveTopUp()"><i class="iconfont iconzhiding"></i></button>
                                    <button @click="bottomUp()"><i class="iconfont iconzhidi"></i></button>
                                </a-button-group>
                                <rx-grid ref="formSettings"
                                         :allowRowSelect="true"
                                         :multiSelect="true"
                                         :bordered="true"
                                         style="min-height:500px;"
                                         :dataSource="dataSource"
                                         :columns="columns"
                                         rowKey="idx_"
                                         :showPage="false">
                                    <span slot="mode" slot-scope="{ text, record ,index}">
                                         <a-select v-model="record.mode">
                                             <a-select-option value="form">{{$ti18('rxForm.formName','表单')}}</a-select-option>
                                             <a-select-option value="list">{{$comi18('rxDialog.dialogList','列表')}}</a-select-option>
                                             <a-select-option value="custom">{{$comi18('rxDialog.custom','自定义')}}</a-select-option>
                                         </a-select>
                                    </span>
                                        <span slot="navigationName" slot-scope="{ text, record ,index}">
                                         <a-input v-model="record.navigationName"></a-input>
                                    </span>
                                    <span slot="formSolution" slot-scope="{ text, record ,index}">
                                        <div v-if="record.mode=='form'">
                                            <span v-if="record.isMain">{{ JSON.parse(text).text }}</span>
                                            <rx-input-button v-else style="width: 95%;" v-model="text"
                                                             :placeholder="i18n('form.solutionConfig','请选择表单方案配置','select')" :showClose="false"
                                                             @click="setFormSolution($event,index)"></rx-input-button>
                                        </div>

                                        <rx-input-button v-else-if="record.mode=='list'" style="width: 95%;" v-model="record.list"
                                                         :placeholder="i18n('form.list','请选择列表','select')" :showClose="false"
                                                         @click="setList($event,index)"></rx-input-button>
                                        <div v-else-if="record.mode=='custom'">
                                             <a-input :title="record.formSolution" style="width: 95%; margin-right: 5px;"
                                                      :placeholder="i18n('list.PagePath','请输入自定义页面路径','input')" v-model="record.formSolution"></a-input>
                                             <a-tooltip>
                                                <span slot="title">
                                                    {{i18n('msg.pathTip','组件路径是src/views目录下的组件,例如路径为src/views/modules/bpm/core/BpmDefList.vue,那么配置为:modules/bpm/core/BpmDefList.vue')}}
                                                </span>
                                             <a-icon type="question-circle-o"/>
                                         </a-tooltip>
                                        </div>

                                </span>
                                    <span  slot="relField"
                                          slot-scope="{ text, record ,index}">
                                    <a-select style="width: 50%" v-if="record.mode=='form'" @focus="getListFields(record)" @change="relFieldChange($event,record)"
                                              :options="curFields" v-model="record.relField"></a-select>
                                        <div v-if="record.mode=='list'">
                                            <a-button shape="circle" icon="setting" @click.stop="setRelConfig(record,index)" />
                                        </div>
                                </span>
                                    <span slot="extendFunc" slot-scope="{ text, record ,index}">
                                    <a-icon type="edit" @click.stop="setExtendFunc(record,index)"/>
                                </span>
                                </rx-grid>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import FormBusinessSolutionApi from '@/api/form/core/formBusinessSolution'
import {RxDialog, BaseFormModel, Util, RxInputButton,Dialog} from "@lowcode/jpaas-common-lib";
import DialogBox from "@/assets/js/DialogBox";
import FormSolutionApi from "@/api/form/core/formSolution.js";
import FormBusSolExtendFunc from "./FormBusSolExtendFunc";
import FormBusSolRelConfig from "./FormBusSolRelConfig";
import FormBoListApi from "@/api/form/core/formBoList";

export default {
    name: 'FormBusinessSolutionEdit',
    mixins: [BaseFormModel],
    components: {
        RxDialog,
        Dialog,
        RxInputButton
    },
    data() {
        return {
            /**
             * 子表列表，以及表格属性
             */
            subTable: {},
            rules: {
                formSolutions: [{required: false, message: this.i18n('form.solutionConfig','请选择表单方案配置','select'), trigger: 'change'}],
                alias: [
                    {required: true, message: this.boentI18n('form.alias','请输入标识','input'), trigger: 'change'},
                    {pattern:/^[a-zA-Z][a-zA-Z0-9_-]*$/,message:this.boentI18n('form.str','不能以数字开头,不能包含【_-】以外的特殊字符！','input')}
                ],
                mainFormSolution: [{required: false, message: this.i18n('form.mainsolution','请选择主表单方案','select'), trigger: 'change'}],
                name: [{required: true, message: this.boentI18n('form.name','请输入名称','input'), trigger: 'change'}],
                navigationPosition: [{required: false, message: this.i18n('form.navPosition','请选择导航栏位置','select'), trigger: 'change'}],
                category: [{required: true, message: this.boentI18n('form.category','请选择分类','select'), trigger: 'change'}],
            },
            columns: [
                {title: this.i18n('form.mode','方式'), dataIndex: "mode", width: '60%', scopedSlots: {customRender: 'mode'}},
                {
                    title: this.i18n('form.navigationName',"导航名称"),
                    dataIndex: "navigationName",
                    width: '60%',
                    scopedSlots: {customRender: 'navigationName'}
                },
                {title: this.$ti18('rxList.config',"配置"), dataIndex: "formSolution", width: '120%', scopedSlots: {customRender: 'formSolution'}},
                {title: this.i18n('form.assoField',"关联字段"), dataIndex: "relField", width: '200%', scopedSlots: {customRender: 'relField'}},
                {title: this.i18n('form.extendFunc',"扩展函数"), dataIndex: "extendFunc", width: '50%', scopedSlots: {customRender: 'extendFunc'}}
            ],
            dataSource: [],
            curFields: [
                {value: "ID_", label: this.$ti18('rxForm.id',"主键"), fieldName: "ID_"}
            ]
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formBusinessSolution",key);
        },
        boentI18n(name,text,key){
            return this.$ti18(name,text,"formBoEntity",key);
        },
        onload_(values) {
            if (values && values.mainFormSolution) {
                this.dataSource = JSON.parse(values.formSolutions);
                //初始化配置
                for (var i = 0; i < this.dataSource.length; i++) {
                    //方式
                    if (!this.dataSource[i].mode) {
                        this.$set(this.dataSource[i], "mode", "form");
                    }
                    //条件
                    if (!this.dataSource[i].extendFunc) {
                        this.$set(this.dataSource[i], "extendFunc", "");
                    }
                }
            }
        },
        get(id) {
            return FormBusinessSolutionApi.get(id);
        },
        save(values,vm) {
            if (!(/^[a-zA-Z][a-zA-Z0-9_]*$/g.test(this.mdl.alias))) {
                this.$message.warning(this.$comi18('business.aliasKey','标识键')+this.boentI18n('msg.checkMsg','标识键要求英文+数字,英文开头!'));
                vm.loading=false;
                return;
            }
            //默认在上方
            if (!this.mdl.navigationPosition) {
                this.mdl.navigationPosition = "horizontal";
            }
            if (this.mdl.mainFormSolution) {
                this.mdl.formSolutions = JSON.stringify(this.dataSource);
            }
            //新增时保存应用ID
            let appId = this.curApp.appId;
            if (appId && !this.pkId) {
                this.mdl.appId = appId;
            }
            return FormBusinessSolutionApi.save(this.mdl);
        },
        addRow() {
            var index = this.dataSource.length + 1;
            this.dataSource.push({
                mode: "form",
                idx_: Util.randomId(),
                navigationName: this.i18n('list.nav',"导航") + index,
                formSolution: "",
                relField: "",
                fieldName: "ID_",
                extendFunc: "",
            });
        },
        removeRows() {
            var selectedRows = this.$refs.formSettings.getSelectedRows();
            for (var i = 0; i < selectedRows.length; i++) {
                //主表单方案不允许删除
                if (selectedRows[i].isMain) {
                    this.$message.warning(this.i18n('msg.priNoDel','主表单方案不允许删除！'));
                    continue;
                }
                for (var j = 0; j < this.dataSource.length; j++) {
                    if (selectedRows[i].idx_ == this.dataSource[j].idx_) {
                        this.dataSource.splice(j, 1);
                    }
                }
            }
        },
        upRow() {
            var selectedRows = this.$refs.formSettings.getSelectedRows();
            for (let selectedRow of selectedRows){
                if (selectedRow && selectedRow.isMain) {
                    this.$notification.warning({
                        message: this.$ti18('rxMsa.actionTips','操作提示'),
                        description:
                            this.i18n('msg.priNoMove','主方案无法移动！'),
                    });
                    return;
                }
            }
            this.$refs.formSettings.moveUp();

        },
        downRow() {
            var selectedRows = this.$refs.formSettings.getSelectedRows();
            for (let selectedRow of selectedRows){
                if (selectedRow && selectedRow.isMain) {
                    this.$message.warning(this.i18n('msg.priNoMove','主方案无法移动！'));
                    return;
                }
            }
            this.$refs.formSettings.moveDown();

        },
        moveTopUp(){
            this.$refs.formSettings.moveTopUp();
        },
        bottomUp(){
            this.$refs.formSettings.moveBottomUp();
        },
        setMainFormSolution(vm) {
            var self = this;
            this.selectSolution(vm, function (data) {
                if (!data) {
                    return;
                }
                //已经存在值时，不需要再复制值
                if(!self.mdl.name && !self.mdl.alias){
                    self.$set(self.mdl,"alias",data.alias);
                    self.$set(self.mdl,"name",data.name);
                }
                vm.setVal(data.id, data.name);
                var value = JSON.stringify({value: data.alias, text: data.name});
                self.$set(self.mdl, "mainFormSolution", value);
                if (self.dataSource.length == 0) {
                    self.dataSource.push({
                        idx_: Util.randomId(),
                        navigationName: data.name,
                        mode: "form",
                        formSolution: value,
                        isMain: true,
                        relField: "ID_",
                        fieldName: "ID_",
                        extendFunc: ""
                    });
                } else {
                    self.dataSource[0].navigationName = data.name;
                    self.dataSource[0].formSolution = value;
                    self.dataSource[0].relField = "ID_";
                    self.dataSource[0].fieldName = "ID_";
                }

            });
        },
        setFormSolution(vm, index) {
            var self = this;
            this.selectSolution(vm, function (data) {
                vm.setVal(data.alias, data.name);
                var value = JSON.stringify({value: data.alias, text: data.name});
                self.dataSource[index].formSolution = value;
                self.dataSource[index].navigationName = data.name;
            });
        },
        selectSolution(vm, callback) {
            var config = {curVm: this, widthHeight: ['1000px', '680px'], data: {multiSelect: false}};
            DialogBox.openSoution(config, function (data) {
                if (callback) {
                    callback(data);
                }
            })
        },
        getListFields(record) {
            this.curFields = [{value: "ID_", label: this.$ti18('rxForm.ID','主键'), fieldName: "ID_"}];
            if (record.formSolution) {
                var alias = JSON.parse(record.formSolution).value;
                FormSolutionApi.getListFields(alias).then(res => {
                    if (res.success) {
                        var ary = [{value: "ID_", label: this.$ti18('rxForm.ID','主键'), fieldName: "ID_"}];
                        for (var i = 0; i < res.data.length; i++) {
                            var obj = res.data[i];
                            var newObj = {};
                            newObj.value = obj["name"];
                            newObj.label = obj["comment"];
                            newObj["fieldName"] = obj["fieldName"];
                            ary.push(newObj);
                        }
                        this.curFields = ary;
                    }

                })
            }
        },
        relFieldChange(value, record) {
            var field = this.curFields.find(item => item.value == value);
            record.fieldName = field.fieldName;
        },
        setExtendFunc(record, index) {
            var lastOne = this.dataSource.length==index+1;
            Util.open({
                component: FormBusSolExtendFunc,
                curVm: this,
                zIndex: 999999,
                widthHeight: ['1024px', '600px'],
                title: this.i18n('form.extendFunc','扩展函数')+this.$ti18('rxList.config','配置'),
                data: {
                    rowData: record,
                    lastOne:lastOne
                },
            }, function (action, data) {
                if (action != "ok") return;
                record.extendFunc = JSON.stringify(data);
            })
        },
        setList(vm, index) {
            var conf={
                curVm: this,
                data: {
                    single: true,
                    isDialog: 'NO'
                },
                widthHeight: ['1000px', '600px']
            };
            var self=this;
            Dialog.openFormBoListDialog(conf,function(self, data) {
                if(data && data[0]){
                    var value = JSON.stringify({value: data[0].key, text: data[0].name});
                    self.$set(self.dataSource[index], "list", value);
                    self.$set(self.dataSource[index], "navigationName", data[0].name);
                }
            });
        },
        setRelConfig(record, index) {
            var solutions=[];
            for (var i = 0; i < this.dataSource.length; i++) {
                if(this.dataSource[i].mode=="form" && this.dataSource[i].formSolution){
                    var formSolution = JSON.parse(this.dataSource[i].formSolution);
                    solutions.push({
                        value:formSolution.value,
                        label:formSolution.text
                    })
                }
            }
            var self=this;
            if(!record.list){
                this.$message.warn(this.i18n('form.list','请选择列表','select'));
                return;
            }
            FormBoListApi.getByKey(JSON.parse(record.list).value).then(res=>{
                var listFields = [];
                var searchJson= JSON.parse(res.data.searchJson);
                searchJson.map(field => {
                    if (field.type == 'income') {
                        var obj = {label: field.fieldLabel, value: field.fieldName};
                        listFields.push(obj);
                    }
                });
                if (listFields.length==0){
                    this.$message.warn("请选择带传入参数的列表");
                    return;
                }
                Util.open({
                    component: FormBusSolRelConfig,
                    curVm: self,
                    zIndex: 999999,
                    widthHeight: ['1024px', '600px'],
                    title: this.i18n('list.assoConfig','关联配置'),
                    data: {
                        rowData: record,
                        solutions:solutions,
                        listFields:listFields,
                        relFields:record.relField?JSON.parse(record.relField):[]
                    },
                }, function (action, data) {
                    if (action != "ok") return;
                    record.relField = JSON.stringify(data);
                })
            });
        },
        getPinyinByName(){
            let name=this.mdl.name
            if (!name){
                return;
            }
            if (this.mdl.alias){
                return;
            }
            this.getPinyin(name).then(res => {
                //去除不可见的特殊符号
                if(res){
                    res=res.replace(/\u200B/g,'');
                }
                this.$set(this.mdl,"alias",res)
            })
        }

    },
    watch: {
        /*"mdl.alias": function (val, oldVal) {
            if (!(/^[a-zA-Z][a-zA-Z0-9_]*$/g.test(val))) {
                this.$set(this.mdl, "alias", oldVal);
                this.$message.warning(this.$comi18('business.aliasKey','标识键')+this.boentI18n('msg.checkMsg','标识键要求英文+数字,英文开头!'));
            }
        }*/
    }
}
</script>
<style>
.relick a {
    margin-right: 10px;
}

</style>
